import xml.etree.ElementTree as ET
import requests
import json
import os

os.chdir(os.path.dirname(os.path.abspath(__file__)))

def get_kodi_credentials():
    """从guisettings.xml获取Kodi认证信息（多路径兼容）"""
    possible_paths = [
        "/storage/.kodi/userdata/guisettings.xml",  # CoreELEC默认路径
        os.path.expanduser("~/.kodi/userdata/guisettings.xml"),
        "/opt/kodi/userdata/guisettings.xml"
    ]
    for path in possible_paths:
        if os.path.exists(path):
            try:
                tree = ET.parse(path)
                root = tree.getroot()
                username_node = root.find(".//setting[@id='services.webserverusername']")
                password_node = root.find(".//setting[@id='services.webserverpassword']")
                username = username_node.text if username_node is not None else "kodi"
                password = password_node.text if password_node is not None else ""
                return {"username": username, "password": password}
            except Exception as e:
                raise RuntimeError(f"解析guisettings.xml失败: {str(e)}")
    raise FileNotFoundError("未找到guisettings.xml文件")

def kodi_jsonrpc(method, params, credentials):
    """通过JSON-RPC请求Kodi数据"""
    url = "http://localhost:8080/jsonrpc"
    headers = {"Content-Type": "application/json"}
    payload = {
        "jsonrpc": "2.0",
        "method": method,
        "params": params,
        "id": 1
    }
    try:
        response = requests.post(
            url,
            data=json.dumps(payload),
            headers=headers,
            auth=(credentials["username"], credentials["password"]),
            timeout=10
        )
        response.raise_for_status()
        return response.json()
    except requests.exceptions.RequestException as e:
        raise ConnectionError(f"API请求失败: {str(e)}")
